package com.gmail.huxiaowi.cblog.dao.impl.jdo;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;

import javax.jdo.JDOException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.orm.jdo.JdoCallback;
import org.springframework.orm.jdo.JdoTemplate;

import com.gmail.huxiaowi.cblog.dao.IGenericDao;

/**
 * Class GenericDaoJDOImpl
 * 
 * @author  huxw
 * @version $Revision:1.0.0, $Date:2010-4-29 下午05:46:14$
 * @param <T>
 */
public abstract class GenericDaoJDOImpl<T> implements IGenericDao<T> {
    protected JdoTemplate jt = null;
    
    private Class<T> clazz = null;
    
    private String entityName = null;
    
    @SuppressWarnings("unchecked")
    public GenericDaoJDOImpl() {
        clazz = (Class<T>) ((ParameterizedType) (this.getClass().getGenericSuperclass())).getActualTypeArguments()[0];
        entityName = clazz.getName();
    }
    
    /* (non-Javadoc)
     * @see com.gmail.huxiaowi.cblog.dao.GenericDao#listSize()
     */
    public long listSize() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
		Integer size = (Integer) jt.execute(new JdoCallback() {
            
            public Object doInJdo(PersistenceManager pm) throws JDOException {
                Query query = pm.newQuery("select count(id) from " + entityName);
                return query.execute();
            }
        });
        return (size == null) ? 0 : size;
    }

    public void setJt(JdoTemplate jt) {
        this.jt = jt;
    }

    /* (non-Javadoc)
     * @see com.gmail.huxiaowi.cblog.dao.GenericDao#delete(java.lang.Object)
     */
    public void delete(T t) {
        // TODO Auto-generated method stub
        jt.deletePersistent(t);
    }

    /* (non-Javadoc)
     * @see com.gmail.huxiaowi.cblog.dao.GenericDao#insert(java.lang.Object)
     */
    public void insert(T t) {
        // TODO Auto-generated method stub
        jt.makePersistent(t);
    }

    /* (non-Javadoc)
     * @see com.gmail.huxiaowi.cblog.dao.GenericDao#queryAll()
     */
    public Collection<T> queryAll() {
        // TODO Auto-generated method stub
        return jt.find(clazz);
    }

    /* (non-Javadoc)
     * @see com.gmail.huxiaowi.cblog.dao.GenericDao#queryById(java.lang.Object)
     */
    public T queryById(Long id) {
        // TODO Auto-generated method stub
        return (T) jt.getObjectById(clazz, id);
    }

    /* (non-Javadoc)
     * @see com.gmail.huxiaowi.cblog.dao.GenericDao#update(java.lang.Object)
     */
    public void update(T t) {
        // TODO Auto-generated method stub
        jt.evict(t);
    }
}
